import json
from collections import defaultdict


class TaxonomyUtil:

    def __init__(self):
        self.index = -1

    @staticmethod
    def get_deep_taxonomy(json_data):
        def find_next(cur, tag):
            if len(cur['children']) > 0:
                children = cur['children']
                for child in children:
                    find_next(child,
                              (tag + child['name']) if tag == '' else (tag + '-' + child['name']))
            else:
                print(tag)

        find_next(json_data, '')

    def build_tree(self, data):
        def get_struct(d):
            self.index += 1
            _d = defaultdict(list)
            for a, *b in d:
                _d[a].append(b)
            return [
                {
                    'id': self.index,
                    'label': a,
                    'children': get_struct(filter(None, b))
                } for a, b in _d.items()
            ]

        components = [i.split('-') for i in data]
        return json.loads(json.dumps(get_struct(components)))

    @staticmethod
    def search_by_id(json_data, id):
        recursive_list = []

        def find_next(d):
            cursor = 0
            for index, item in enumerate(d):
                if id > d[index]['id']:
                    cursor = index
                    continue
                elif id == d[index]['id']:
                    recursive_list.append(id)
                    return True
                else:
                    break
            recursive_list.append(d[cursor]['id'])
            find_next(d[cursor]['children'])

        find_next(json_data)
        return recursive_list


if __name__ == '__main__':

    with open('../data/chest_graph_2021_07_15.json', 'r', encoding='UTF-8') as f:
        json_data = json.load(f)
        TaxonomyUtil.get_deep_taxonomy(json_data)

    results = TaxonomyUtil().build_tree(['肺纹理-走形-垂柳状',
                                         '肺纹理-走形-紊乱',
                                         '肺纹理-境界-模糊',
                                         '肺纹理-粗细-纤细',
                                         '肺纹理-粗细-增粗',
                                         '肺纹理-数量-消失',
                                         '肺纹理-数量-减少',
                                         '肺纹理-数量-增多'])

    print(json.dumps(results, ensure_ascii=False))

    data = []
    with open('../data/chest_deep_taxonomy_2021_07_15.txt', 'r', encoding='UTF-8') as f:
        lines = f.readlines()
        for i in lines:
            data.append(i.strip())
    data.reverse()
    data = TaxonomyUtil().build_tree(data)
    print(json.dumps(data, ensure_ascii=False))

    recursive_list = TaxonomyUtil.search_by_id(data, 2607)
    for index, item in enumerate(data):
        if recursive_list[0] == item['id']:
            head_node_index = index
            break

    # 用户选择正常
    if data[head_node_index]['children'][0]['id'] == recursive_list[1]:
        start_id = data[head_node_index]['children'][1]['id']
        if head_node_index == len(data) - 1:
            end_id = 5000
        else:
            end_id = data[head_node_index + 1]['id']
        exclusive_list = [i for i in range(start_id, end_id)]
    # 用户选择异常
    else:
        exclusive_list = [data[head_node_index]['children'][0]['id']]

    print(exclusive_list)
